package com.example.dense_rack_server;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.HostTemHum;
import com.example.dense_rack_server.mapper.HostTemHumMapper;
import com.example.dense_rack_server.service.HostTemHumService;
import com.example.dense_rack_server.utils.CabinetLoginStatus;
import com.example.dense_rack_server.utils.Netty.NettyServer;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@MapperScan("com.example.dense_rack_server.mapper")
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) // 直接关闭security接口拦截
@Slf4j
public class Application implements CommandLineRunner {


    @Resource
    public HostTemHumService hostTemHumService;

    // 静态方法注入bean解决方案 在springboot的启动类中，定义static变量ApplicationContext，利用容器的getBean方法获得依赖对象
    public static ConfigurableApplicationContext ac;

    public static void main(String[] args) {
        ac = SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) {
        new Thread(() ->{
            try {
                new NettyServer(9008).run();
            } catch (Exception e) {
                log.error("Netty启动错误", e);
            }
        }).start();
        // 删除多余天数库区温湿度
        List<HostTemHum> list = hostTemHumService.list();
        Date nowDate = DateUtil.date();
        Date startDate = DateUtil.offset(nowDate, DateField.MONTH, -1);
        Date newDate = DateUtil.offset(startDate, DateField.DAY_OF_MONTH, -1);
        String formatDate = DateUtil.formatDate(newDate);
        boolean success = hostTemHumService.remove(new QueryWrapper<HostTemHum>().le("create_time", formatDate));
        log.info("清理{}之前的数据成功:{}", formatDate, success);
    }

    public static CabinetLoginStatus cabinetLoginStatus;

}
